﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace KPIS.GERP.GHRMS.MODEL
{
	public static class Caption
	{
		private static string FileName
		{
			get
			{
				return HttpContext.Current.Server.MapPath(
					HttpContext.Current.Request.Path.Replace(".aspx", ".txt"));
			}
		}

		public static string Get(string paramName)
		{
			string result = paramName, fileName = FileName;

			// Case 1 : Wrong usage case, not define param
			paramName = paramName.Trim();
			if (String.IsNullOrEmpty(paramName)) 
				throw new Exception("Not define param");

			// Case 1 : File not exist, result is param name, create file, insert parametor line to file.
			if (!File.Exists(fileName))
			{
				// Create
				using (FileStream fs = File.Create(fileName))
				{
					Byte[] info = new UTF8Encoding(true).GetBytes(String.Format("{0}={0}",
						                                                        paramName));
					// Insert parametor line to file.
					fs.Write(info, 0, info.Length);
				}
			}
			else
			{
				bool found = false;
				using (var file = new StreamReader(fileName))
				{
					string line;
					while ((line = file.ReadLine()) != null)
					{
						var arrayParamWithValues = line.Split('=');
						if (!line.StartsWith("#") && arrayParamWithValues.Count() >= 2 &&
						    arrayParamWithValues[0].Trim() == paramName)
						{
							result = line.Substring(line.IndexOf("=", StringComparison.Ordinal));
							found = true;
						}
					}

				}

				if (!found)
					using (StreamWriter sw = File.AppendText(fileName))
					{
						sw.WriteLine(Environment.NewLine + "{0}={0}", paramName);
					}
			}

			return result;
		}
	}
}